package com.ruoyi.user.service.thirdpay.wx;

import com.ruoyi.user.model.Constant;
import com.ruoyi.user.service.thirdpay.wx.model.GetWxPublicKey;
import com.ruoyi.user.service.thirdpay.wx.model.GetWxPublicKeyResult;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.StringEntity;
import weixin.popular.api.PayMchAPI;
import weixin.popular.client.LocalHttpClient;
import weixin.popular.util.MapUtil;
import weixin.popular.util.SignatureUtil;
import weixin.popular.util.XMLConverUtil;

import java.nio.charset.Charset;
import java.util.Map;


/**
 * @author houyong
 */
public class WblhPayMchAPI extends PayMchAPI {

    private static final ThreadLocal<Boolean> sandboxnew = new ThreadLocal<Boolean>();

    /**
     * 仿真测试 开始
     *
     * @since 2.8.6
     */
    public static void sandboxnewStart() {
        sandboxnew.set(true);
    }

    /**
     * 仿真测试 结束
     *
     * @since 2.8.6
     */
    public static void sandboxnewEnd() {
        sandboxnew.set(null);
    }

    private static String baseURI() {
        if (sandboxnew.get() == null) {
            return MCH_URI;
        } else {
            return MCH_URI + "/sandboxnew";
        }
    }

    public static GetWxPublicKeyResult getPublicKey(GetWxPublicKey getWxPublicKey, String mchKey) {
        Map<String, String> sortedMap = MapUtil.objectToMap(getWxPublicKey);
        String sign = SignatureUtil.generateSign(sortedMap, "MD5", mchKey);
        getWxPublicKey.setSign(sign);
        String requestXML = XMLConverUtil.convertToXML(getWxPublicKey);
        HttpUriRequest httpUriRequest = RequestBuilder.post()
                .setHeader(xmlHeader)
                .setUri("https://fraud.mch.weixin.qq.com/risk/getpublickey")
                .setEntity(new StringEntity(requestXML, Charset.forName(Constant.UTF8_ENCODING)))
                .build();
        return LocalHttpClient.keyStoreExecuteXmlResult(getWxPublicKey.getMch_id(), httpUriRequest, GetWxPublicKeyResult.class, "MD5", mchKey);
    }


}
